package com.ag.lzw.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ag.bean.TbUser;
import com.ag.common.BaseAction;
import com.ag.common.EventUtil;
import com.ag.common.IDUtil;
import com.ag.common.IPermissionService;
import com.ag.lzm.utils.JacksonMapper;
import com.ag.lzw.common.DateHandeler;
import com.ag.lzw.dao.LzwTbProposeDAO;
import com.ag.lzw.dao.LzwTbUserDAO;
import com.ag.lzw.service.HandelTasks;
import com.ag.lzw.service.IdentifyService;
import com.ag.lzw.service.impl.Lzw_IIDServiceImpl;
import com.ag.lzw.vo.NewTaskVo;
import com.ag.zhh.service.ContactLogService;

/**
 * @author zhiweiofli 
 * 添加任务的action类
 * */
@Scope("prototype")
@Controller("addTaskAction")
public class AddTaskAction extends BaseAction implements SessionAware{
	private static final long serialVersionUID = 891781047149206372L;
	private static final Logger logger = Logger.getLogger(AddTaskAction.class);
	 
    @Resource(name="lzw_IIDServiceImpl")
	Lzw_IIDServiceImpl idSerImpl;
	@Resource(name="handelTaskImpl")
	private HandelTasks handelTask;
	@Resource(name="ContactLogService")
	private ContactLogService contactLogService;
	@Resource(name="lzwTbUserDAO")
	private LzwTbUserDAO userDAO;
	@Resource(name="lzwTbProposeDAO")
	LzwTbProposeDAO proposeDAO;
	@Resource(name="IdentifyServiceImpl")
    private IdentifyService identifyServ;
	
	/**
	 * 调用权限服务逻辑组件
	 */
	@Resource(name="PermissionServiceImpl")
	private IPermissionService pms;
	/**
	 * 提供Map<String, Object>类型的Session变量，用来保存Struts2注入的Session上下文
	 */
	private Map<String, Object> sessionMap;

	
	@Override
	public void setSession(Map<String, Object> session) {
		this.sessionMap = session;
	}

	
	/**返回新任务ID的集合的方法
	 * */
	public String getNewTaskNo() {
		newTaskIds = idSerImpl.findTablePK(IDUtil.TB_TASK, num);
		if (newTaskIds != null) {
			return "gettaskno_OK";
		} else {
			errMsg = "获取任务ID失败，请重试！";
			return "gettaskno_ERROR";
		}
	}

	/**保存新任务的方法，解析从前台传来的json字符串，并保存
	 * @return save_newtask_succ String                            
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 * */
	public String saveNewTask(){
        TbUser currentUser = this.pms.getCurrentUser(sessionMap);
		String uid = currentUser.getUId();   //获取当前用户ID
		logger.info("Current userID:"+uid);
		
		logger.info("===========saveNewTask========");
		List<NewTaskVo> tasks = new ArrayList<NewTaskVo>();
		ObjectMapper mapper = JacksonMapper.getInstance();   //JSON解析器
		JsonNode jsonNode = null;
		
		String eventID = null;
		if(isCurrentLeader()){  //保存任务前，判断当前用户是否为指挥长角色
			try {
				//尝试从session中取出当前的事件ID
				Object obj = this.getSessionAttribute(EventUtil.PROCESSING_EVENT_ID); 
				if(obj!=null){
					eventID = obj.toString();
				} else {
					errMsg = "操作失败！";
					return "save_newtask_false";
				}
			} catch (Exception e) {
				e.printStackTrace();
				errMsg = "操作失败！";
				return "save_newtask_false";
			}
		} else {  //非指挥长，事件ID从前台获得
			logger.info("cunrrent event id is: "+taskEventID);
			if (taskEventID != null && taskEventID.length() > 0 && !(taskEventID.equals("null")) ) {  //前台cookie传回的事件ID
				eventID = taskEventID;
			} else {
				errMsg = "操作失败！";
				return "save_newtask_false";
			}
		}
		
		logger.info("------Save New Tasks For Eid:"+eventID);
		try {
			logger.info("JSON:"+newTaskJson);
			jsonNode = mapper.readValue(newTaskJson, JsonNode.class);
			JsonNode node = jsonNode.get("TaskInfo");
			Iterator<JsonNode> nodes = node.getElements();
			
			//遍历TaskInfo下的所有节点内容
			while (nodes.hasNext()) {
				JsonNode obj = nodes.next();
				
				if(obj.size()!= 0 && obj != null ){
					NewTaskVo ntv = new NewTaskVo();
					
					//用vo进行重新包装
					ntv.setB(uid);     //把当前用户的信息保存在任务表的B字段，用于记录任务的分派者     
					
					ntv.setEId(eventID);
					logger.info("New Task of Event:"+eventID);
					ntv.setId(obj.get("id").getTextValue());
					logger.info("New Task Id :"+ntv.getId());
					
					//******************************************************
					String filename = obj.get("filename").getTextValue();
					logger.info("filename:"+filename);
					if(filename.equals("")){
						ntv.setFilename(null);
					} else {
						ntv.setFilename(filename);
					}
					
					//String[] fileNameArr = filename.split(",");
					
					String fileid = obj.get("fileid").getTextValue();
					logger.info("fileid:"+fileid);
					if(fileid.equals("")){
						ntv.setFileid(null);
					} else {
						ntv.setFileid(fileid);
					}
					
					if(taskFatherID.equals("null") || taskFatherID.length()==0){
						ntv.setFid(null);
					} else {
						ntv.setFid(taskFatherID); //设置父任务ID---by hmk 
					}
					ntv.setName(obj.get("name").getTextValue());
					ntv.setContext(obj.get("context").getTextValue());
					ntv.setTime(obj.get("time").getTextValue());
					
					ntv.setDeptID(obj.get("deptID").getTextValue());
					ntv.setUserID(obj.get("uid").getTextValue());
					
					tasks.add(ntv);
					/*
					TreeNode tn = lts.getTreeNodeById(ntv.getDeptID());
					if(tn!=null){
						
						UserDept ud = (UserDept)tn.getBindData();

						UserDeptContact udc = ud.getTbUser();
						if(udc==null){
							logger.info("The Dept has not Leader!");
							errMsg = "操作失败，该部门没有负责人！";
							return "save_newtask_false";
						} else {
							String uid = udc.getUId();
							//String uid = ((UserDept)tn.getBindData()).getTbUser().getUId();
							ntv.setUserID(uid);
							logger.info("The dept,s leader is :"+uid);
						}
					} else {
						logger.info("Cannot Save New Task beacause of no Leader for the Dept Id");
						errMsg = "操作失败！没有下级部门";
						return "save_newtask_false";
					}
					*/
					//JsonNode node = nodes.next().get("data");
					
					try  {
						TbUser toUser = userDAO.findById(ntv.getUserID());
						String currentTime = DateHandeler.DateToString(new Date());
						String smsContext = "应急人员："+currentUser.getUName()+"于"+currentTime+"向你下发一任务:"+ntv.getName()+"，该任务属于事件："+eventID+"。请迅速登录应急指挥系统，查看详情。谢谢！";
						//发短信的步骤
						sendSms(currentUser.getUName(), toUser.getUName(), toUser.getUId(), toUser.getUPhone(), smsContext, eventID);
					} catch(Exception e){
						e.printStackTrace();
					}
				}
				
			}
		} catch (JsonParseException e) {
			logger.info("JsonParseException------1");
			errMsg = "操作失败！";
			logger.debug(e);
		} catch (JsonMappingException e) {
			logger.info("JsonMappingException------2");
			errMsg = "操作失败！";
			logger.debug(e);
		} catch (IOException e) {
			logger.info("IOException------3");
			errMsg = "操作失败！";
			logger.debug(e);
		}
		//调用属性handelTask的方法保存内容
		logger.info("Saving New Tasks ,newtasks size:"+tasks.size());
		if(handelTask.saveTasks(tasks)){
			logger.info("Save New Tasks Success!");
			return "save_newtask_succ";
		}
		else{
			logger.info("Save New Tasks Fail!");
			errMsg = "任务保存失败，请重新登录再试！";
			return "save_newtask_false";
		}
	}
	
	/**
	 * 发短信通知的方法封装
	 * @param ctCaller
	 * @param ctCalled
	 * @param ctCalledUId
	 * @param ctCalledNumber
	 * @param ctSmsContent
	 * @param eventId
	 * @return
	 */
	private boolean sendSms(String ctCaller, String ctCalled, String ctCalledUId, String ctCalledNumber, String ctSmsContent, String eventId){
		//发短信的步骤
		if(this.contactLogService.addOneMessageContactLogByEvent(ctCaller, ctCalled, ctCalledUId, ctCalledNumber, ctSmsContent, eventId)){
			return true;
		} else {
			return false;
		}
	}
	
	private boolean isCurrentLeader(){
		TbUser currentUser = this.pms.getCurrentUser(sessionMap);

		String uid = currentUser.getUId(); // 获取当前用户ID
		logger.info(">>>Current userID:" + uid);

		// 根据传入的参数和当前用户的信息，判断当前用户是否为指挥长的角色
		logger.info(">>>looking for leader...");
		try {
			if(this.getSessionAttribute(EventUtil.PROCESSING_EVENT_ID)!=null){
				return identifyServ.isLeader(uid, getSessionAttribute(EventUtil.PROCESSING_EVENT_ID));
			}
		} catch (Exception e) {
			e.printStackTrace();
			errMsg = "操作失败！请重试...";
			return false;
		}
		return false;
	}
	

	//请求添加新任务的数目
	private int num;
	//将返回前台页面的id的集合
	private List<String> newTaskIds;
	// private Map<String,TaskInfo> newTasks = new HashMap<String,TaskInfo>();
	//前台页面所提交的任务的保存属性
	private String newTaskJson;
	//出错信息返回
	private String errMsg;
	//接受事件ID
	private String taskEventID; 
	//父任务ID
	private String taskFatherID; 

	// 以下为属性的get，set方法
	public void setNum(int num) {
		this.num = num;
	}

	public List<String> getNewTaskIds() {
		return newTaskIds;
	}
	
	public void setNewTaskJson(String newTaskJson) {
		this.newTaskJson = newTaskJson;
	}
	public String getErrMsg() {
		return errMsg;
	}

	public void setTaskEventID(String taskEventID) {
		this.taskEventID = taskEventID;
	}

	public void setTaskFatherID(String taskFatherID) {
		this.taskFatherID = taskFatherID;
	}
}
